import pytest
import allure

from CaseAW.winapp import winApp

globalapp=winApp()
flag=0#flag为0是，为正常执行，不为0,为可靠性执行


@pytest.fixture(scope="session",autouse=True)
def ssesion_setup():
    global  chandao_session,system_platform
    dcax_log_move()
    system_platform=sys.getwindowsversion()
    chandao_session=new_chandao()
    chandao_session.login()

@pytest.fixture(scope="session",autouse=True)
def countiuns_run():
    if flag!=0:
        subprocess.Popen(r".\start.bat")
        log.info("start!!!!")
        yield
        log.warning("开始清理环境")
        try:
            globalapp.closedown()
        except:
            pass
        os.popen("taskkill /f /im 'DCAX-Grid.exe'")
        log.info("done!!!")
        time.sleep(5)
    else:
        yield
        pass

@pytest.fixture(scope="function")
def setup_teardown():
    if flag!=0:
        try:
            globalapp.driver.find_element_by_name("文件(F)").click()
            globalapp.driver.find_element_by_name("新建工程").click()
            globalapp.clear_text_table()
        except Exception as e:
            pass
        log.info("start!!!!")
        time.sleep(2)
        cwdpath=os.path.abspath(__file__)
        basename=os.path.basename(__file__)
        filespath=cwdpath.replace(basename,"..\files")
        try:
            path=str(request.fspath)
            case_id=re.search("test_(\d+)",path).group(1)
            log.info("获取的ID为:%s"%case_id)
            result=chandao_session.get_case_info(case_id)
            result["filespath"]=filespath
        except:
            log.warning("******用例信息，获取失败******")
            result={"filespath":filespath}
        yield result
        try:
            #恢复窗口默认
            globalapp.set_defult_windows()
        except Exception as e:  
            log.info(e)
            pass
        log.info("done!!!")
        time.sleep(2)
    else:
        try:
            #规避前面崩溃影响后面用例
            globalapp.driver.find_element_by_xpath("//Window//Button[@Name='关闭程序(C)']").click()
        except Exception as e:
            pass
        subprocess.Popen(r".\start.bat")
        log.info("start!!!!")
        time.sleep(5)
        try:
            globalapp.driver.find_element_by_name("视图").click()
            globalapp.driver.find_element_by_name("显示logo").click()
        except Exception:
            pass
        cwdpath=os.path.abspath(__file__)
        basename=os.path.basename(__file__)
        filespath=cwdpath.replace(basename,"..\files")
        try:
            path=str(request.fspath)
            case_id=re.search("test_(\d+)",path).group(1)
            log.info("获取的ID为:%s"%case_id)
            result=chandao_session.get_case_info(case_id)
            result["filespath"]=filespath
        except:
            log.warning("******用例信息，获取失败******")
            result={"filespath":filespath}
        yield result
        log.warning("开始清理环境")
        try:
            #恢复窗口默认
            globalapp.set_defult_windows()
        except Exception as e:  
            log.info(e)
            pass
        try:
            globalapp.closedown()
        except:
            pass
        os.popen("taskkill /f /im 'DCAX-Grid.exe'")
        time.sleep(5)


@pytest.hookimpl(hookwrapper=True,tryfirst=True)
def pytest_runtest_makereport(item,call):
    outcome =yield
    report=outcome.get_result()
    # if report.when=="call" and report.failed:
    #     with allure.step("失败截图"):
    #         allure.attach(globalapp.driver.get_screenshot_as_png(),name="失败截图",attachment_type=allure.attachment_type.PNG)

    case_num=item.nodeid.split("_")[-1]

    #执行前，手写脚本记录用例执行日志
    if report.when=="setup" and "test_ats" not in report.fspath and not report.failed:
        log.critical("开始执行用例({case_num})",extra={"status":"running","case_num":case_num})
    #执行前，手写脚本记录用例失败日志
    if report.when=="setup" and "test_ats" not in report.fspath and report.failed:
        log.error(report.longreprtext)
    #执行中，失败执行
    if report.when=="call" and report.failed:
        if hasattr(report,"fspath") and "GUITest" in report.fspath:
            return
        with allure.step("失败截图"):
            #执行结束，成功的手写脚本
            log.error(f"用例执行失败({case_num}):{report.longreprtext}",extra={"status":"failed","case_num":case_num})
            allure.attach(globalapp.driver.get_screenshot_as_png(),"failedpng",attachment_type=allure.attachment_type.PNG)
            DCDocxWidget_list=globalapp.driver.find_elements_by_class_name("DCDocxWidget")
            for item in DCDocxWidget_list:
                #print(item.get_attribute("Name"))
                if item.get_attribute("Name")!=None:
                    roi,ws=globalapp.insert_xlxs(item)
                    allure.attach(roi,"面板图",allure.attachment_type.PNG)
                    allure.attach(ws,"元素信息",allure.attachment_type.CSV)
    if report.when=="call":
        lof.dumf=dcax_log_attach()
        if lof!=None:
            allure.attach.file(lof,name="dcax_log")
        if dump!=None:
            allure.attach.file(dump,name="dcax_dump")
    #执行结束，失败的手写脚本，记录错误失败信息
    elif report.when=="call" and not report.failed and "GUITest" in report.fspath:
        log.crictical(f"执行用例结束({case_num})",extra={"status":"finished","case_name":case_num})
